package com.jc.camerascan.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jc.camerascan.R;
import com.jc.camerascan.activity.MainActivity;
import com.jc.camerascan.core.BaseActivity;
import com.jc.camerascan.core.http.bean.CustomApiResult;
import com.jc.camerascan.core.http.callback.TipCallBack;
import com.jc.camerascan.entity.GetWeChatAccessTokenBean;
import com.jc.camerascan.entity.GetWeChatInfoInfoBean;
import com.jc.camerascan.entity.event.WXLoginEvent;
import com.jc.camerascan.entity.event.WXLoginGetTokenEvent;
import com.jc.camerascan.entity.login.PostWxLoginBean;
import com.jc.camerascan.entity.login.WxLoginBean;
import com.jc.camerascan.utils.JurisdictionUtils;
import com.jc.camerascan.utils.MMKVUtils;
import com.jc.camerascan.utils.XToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.button.SmoothCheckBox;
import com.xuexiang.xui.widget.button.roundbutton.RoundButton;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.system.DeviceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jc.camerascan.wxapi.WxConstants.WX_APP_ID;

/**
 * @ProjectName: PhotoRecognition
 * @Package: com.jc.camerascan.login
 * @ClassName: LoginActivity
 * @Description: java类作用描述
 * @Author: XuChi
 * @CreateDate: 2020/7/16 16:31
 * @Version: 1.0
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.login)
    RoundButton login;
    @BindView(R.id.skip)
    TextView skip;
    @BindView(R.id.xieyi)
    TextView xieyi;
    @BindView(R.id.yinsi)
    TextView yinsi;
    @BindView(R.id.checkbox)
    SmoothCheckBox checkbox;

    private IWXAPI api;

    private boolean isFisrtGetWeChatAccessToken = true;

    private boolean isFisrtGetWXLogin = true;

    private GetWeChatAccessTokenBean weChatAccessTokenBean;

    private GetWeChatInfoInfoBean weChatInfoInfoBean;


    public static void start(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        isFisrtGetWeChatAccessToken = true;
        isFisrtGetWXLogin = true;
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, true);
        api.registerApp(WX_APP_ID);
        initView();
    }

    private void initView() {
        StatusBarUtils.translucent(this);
        checkbox.setChecked(true);
        checkbox.setOnCheckedChangeListener(new SmoothCheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SmoothCheckBox checkBox, boolean isChecked) {
                MMKVUtils.put("key_agree_privacy", isChecked);
            }
        });
        xieyi.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        xieyi.getPaint().setAntiAlias(true);//抗锯齿
        yinsi.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        yinsi.getPaint().setAntiAlias(true);//抗锯齿
    }

    @OnClick(R.id.login)
    public void onLoginClicked() {
        if (JurisdictionUtils.isAgree()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "拍照扫描微信登录";
            api.sendReq(req);
        } else {
            XToastUtils.warning("请先同意用户协议及隐私政策");
        }
    }

    @OnClick(R.id.skip)
    public void onSkipClicked() {
        if (JurisdictionUtils.isAgree()) {
            ActivityUtils.startActivity(MainActivity.class);
            finish();
        } else {
            XToastUtils.warning("请先同意用户协议及隐私政策");
        }
    }

    @OnClick(R.id.xieyi)
    public void onXieyiClicked() {
    }

    @OnClick(R.id.yinsi)
    public void onYinsiClicked() {
    }

    /**
     * 微信获取AccessToken 回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WXLoginGetTokenEvent event) {
        if (isFisrtGetWeChatAccessToken) {
            isFisrtGetWeChatAccessToken = false;
            GetWeChatAccessToken(event.getCode());
        }
    }

//    /**
//     * 微信获取信息 回调
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(WXLoginGetInfoEvent event) {
//        GetWeChatInfo();
//    }

    /**
     * 微信获取信息 回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WXLoginEvent event) {
        if (isFisrtGetWXLogin) {
            isFisrtGetWXLogin = false;
            GetWXLogin();
        }
    }

    public void GetWeChatAccessToken(String code) {
        XHttp.get("/api/WeiXin/GetWeChatAccessToken")
                .params("code", code)
                .execute(new CallBackProxy<CustomApiResult<GetWeChatAccessTokenBean>, GetWeChatAccessTokenBean>(new TipCallBack<GetWeChatAccessTokenBean>() {
                    @Override
                    public void onSuccess(GetWeChatAccessTokenBean response) throws Throwable {
                        weChatAccessTokenBean = response;
                        GetWeChatInfo();
                    }

                    @Override
                    public void onError(ApiException e) {
//                        super.onError(e);
                        isFisrtGetWeChatAccessToken = true;
                    }
                }) {
                });
    }

    public void GetWeChatInfo() {
        XHttp.get("https://api.weixin.qq.com/sns/userinfo")
                .params("access_token", weChatAccessTokenBean.getAccess_token())
                .params("openid", weChatAccessTokenBean.getOpenid())
                .params("lang", "zh_CN")
                .keepJson(true)
                .execute(new TipCallBack<String>() {
                    @Override
                    public void onSuccess(String response) throws Throwable {
                        weChatInfoInfoBean = JsonUtil.fromJson(response, GetWeChatInfoInfoBean.class);
                        EventBus.getDefault().post(new WXLoginEvent());
                    }
                });
    }

    private void GetWXLogin() {
        PostWxLoginBean bean = new PostWxLoginBean();
        bean.setAccess_token(weChatAccessTokenBean.getAccess_token());
        bean.setApp_code("10000");
        bean.setCity(weChatInfoInfoBean.getCity());
        bean.setHeadimgurl(weChatInfoInfoBean.getHeadimgurl());
        bean.setNickname(weChatInfoInfoBean.getNickname());
        bean.setOpenid(weChatInfoInfoBean.getOpenid());
        bean.setProvince(weChatInfoInfoBean.getProvince());
        bean.setSex(weChatInfoInfoBean.getSex());
        bean.setUnionid(weChatInfoInfoBean.getUnionid());
        bean.setDevice_brand(Build.MANUFACTURER);
        bean.setDevice_info(new Gson().toJson(DeviceUtils.getDeviceInfos()));
        bean.setDevice_id(DeviceUtils.getAndroidID());
        XHttp.post("/api/WeiXin/WxLogin")
                .upJson(JsonUtil.toJson(bean))
                .execute(new CallBackProxy<CustomApiResult<WxLoginBean>, WxLoginBean>(new TipCallBack<WxLoginBean>() {
                    @Override
                    public void onSuccess(WxLoginBean response) throws Throwable {
                        if (response.getToken() != null && !response.getToken().isEmpty()) {
                            MMKVUtils.put("xc_access_token", response.getToken());
                        }
                        MMKVUtils.put("is_login", true);
                        ActivityUtils.startActivity(MainActivity.class);
                        finish();
                    }

                    @Override
                    public void onError(ApiException e) {
//                        super.onError(e);
                        isFisrtGetWXLogin = true;
                    }
                }) {
                });
    }

}
